<script setup>
import { onMounted, watch, onBeforeUnmount } from "vue";
import { useDark } from '@vueuse/core';
import ace from "ace-builds";
import ejsJava from 'ace-builds/src-noconflict/mode-ejs?url'
import monokaiTheme from 'ace-builds/src-noconflict/theme-monokai?url'
import oneDarkTheme from 'ace-builds/src-noconflict/theme-one_dark?url'

ace.config.setModuleUrl("ace/mode/ejs", ejsJava);
ace.config.setModuleUrl("ace/theme/monokai", monokaiTheme);
ace.config.setModuleUrl("ace/theme/one_dark", oneDarkTheme);

const isDark = useDark()
const props = defineProps(["language"]);
const emit = defineEmits(['change', 'save']);
const getTheme = () => {
    return isDark.value ? 'ace/theme/monokai' : "ace/theme/one_dark"
};

let aceEditor;
onMounted(() => {
    aceEditor = ace.edit(document.getElementById("ace-editor"), {
        theme: getTheme(),
        mode: 'ace/mode/ejs',
        tabSize: 2,
        fontSize: 14,
        wrap: true,
        enableSnippets: true,
        showLineNumbers: true,
        enableLiveAutocompletion: true,
        enableBasicAutocompletion: true,
        scrollPastEnd: true,
        highlightActiveLine: true,
    })
    aceEditor.on('change', () => {
        emit('change', aceEditor.getValue())
    })
    aceEditor.commands.addCommand({
        name: 'save',
        bindKey: { win: 'Ctrl-S', mac: 'Command-S' },
        exec: () => {
            emit('save');
        }
    });
});
onBeforeUnmount(() => {
    aceEditor.destroy()
    aceEditor.container.remove();
})
watch(() => isDark.value, () => {
    aceEditor.setTheme(getTheme());
});

const setValue = (value) => {
    aceEditor.setValue(value)
}
defineExpose({ setValue })
</script>

<template>
    <div class="w-full h-full flex flex-col">
        <div class="border-b border-color h-7">

        </div>
        <div class="w-full h-0 flex-1" id="ace-editor"></div>
    </div>
</template>
<style scoped></style>